//
//  HXScrollFundView.m
//  HXJBP
//
//  Created by zhangjingle on 13-12-12.
//  Copyright (c) 2013年 zhang jingle. All rights reserved.
//
#import "HXScrollFundView.h"
#import "HXFundTransferDataView.h"

@interface HXScrollFundView()
{
    CGFloat scrollWidth;
    int curPage;
    int totalPage;
    BOOL isSpecial;
}
@property (nonatomic, retain) UIView * customView;
@property (nonatomic, retain) IBOutlet UIScrollView * scrollView;
@property (nonatomic, retain) NSMutableArray * fundDataArray;
@property (nonatomic, retain) NSMutableArray * currentFundArray;
@property (nonatomic, retain) HXImageDownloader * imageDownloader;
@end

@implementation HXScrollFundView

-(void)dealloc
{
    RELEASE_SAFELY(_scrollView);
    RELEASE_SAFELY(_customView);
    RELEASE_SAFELY(_fundDataArray);
    RELEASE_SAFELY(_currentFundArray);
    RELEASE_SAFELY(_imageDownloader);
    [super dealloc];
}

-(id)initWithCoder:(NSCoder *)aDecoder
{
    self = [super initWithCoder:aDecoder];
    if (self) {
        self.customView = [[[NSBundle mainBundle] loadNibNamed:@"HXScrollFundView" owner:self options:nil] objectAtIndex:0];
        [self setupCustomView];
        
    }
    
    return self;
}
-(void)setupCustomView
{
    [self setAutoresizingMask:UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleWidth];
    CGRect rect = self.frame;
    rect.origin.y = 0;
    rect.origin.x = 0;
    self.customView.frame = rect;
    [self addSubview:self.customView];
    
    self.fundDataArray    = [[[NSMutableArray alloc] init] autorelease];//传入的数据源
    self.currentFundArray = [[[NSMutableArray alloc] init] autorelease];//当前展示的数据源
    
    curPage = 1;
    
    isSpecial = NO;
    
    scrollWidth = self.frame.size.width;
    
    [self initView];
}
-(void)initView
{
    CGRect imageViewRect = CGRectMake(5, 5, 310, 215);
    CGRect fundViewRect = CGRectMake(0, imageViewRect.origin.y + imageViewRect.size.height + 8, self.customView.frame.size.width, 82);
    UIImageView * imageView = [[UIImageView alloc] initWithFrame:imageViewRect];
    imageView.image = [UIImage imageNamed:@"fund_banner.jpg"];
    HXFundTransferDataView * dataView = [[HXFundTransferDataView alloc] initWithFrame:fundViewRect];
    [dataView loadData:nil];
    [self.scrollView addSubview:imageView];
    [imageView release];
    [self.scrollView addSubview:dataView];
    [dataView release];
}
-(void)setupData:(NSArray *)dataArray
{
    [self handleViewDataWith:dataArray];    //1.接受到数据以后处理数据和设置页面
    [self refreshScrollView];               //2.刷新页面
    [self downloadImage];                   //3.下载图片
}
-(void)handleViewDataWith:(NSArray *)dataArray
{
    if ([dataArray count] == 1){            //一条数据不让scrollView 滑动 （不然在pop的时候会crash）
        self.scrollView.scrollEnabled = NO;
        self.scrollView.delegate = nil;
    }else if ([dataArray count] == 2) {     //因为实现循环滑动必须有三条以上的数据，所以多加一次数据，2条数据情配置成4条
        [self.fundDataArray addObjectsFromArray:dataArray];
        isSpecial = YES;
    }
    [self.fundDataArray addObjectsFromArray:dataArray];
    
    totalPage = (self.fundDataArray.count > 0)?self.fundDataArray.count:1;
    [self.scrollView setContentSize:CGSizeMake(self.scrollView.frame.size.width * totalPage,
                                               self.scrollView.frame.size.height)];
}
-(void)refreshScrollView
{
    
    NSArray *subViews = [self.scrollView subviews];
    if([subViews count] != 0) {
        [subViews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    }
    [self getCurrentFundArrayWithCurpage:curPage];
    CGRect imageViewRect = CGRectMake(5, 5, 310, 215);
    CGRect fundViewRect = CGRectMake(0, imageViewRect.origin.y + imageViewRect.size.height + 8, self.customView.frame.size.width, 82);
    for (int i = 0; i < self.currentFundArray.count; i++) {
        HXFundTransferArrayModel * infoModel = (HXFundTransferArrayModel *)[self.currentFundArray objectAtIndex:i];
        UIImageView * imageView = [[UIImageView alloc] initWithFrame:imageViewRect];
        imageView.image = infoModel.fundImage;
        imageView.userInteractionEnabled = YES;
        UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self
                                                                                    action:@selector(handleTap:)];
        [imageView addGestureRecognizer:singleTap];
        [singleTap release];
        
        HXFundTransferDataView * dataView = [[HXFundTransferDataView alloc] initWithFrame:fundViewRect];
        [dataView loadData:infoModel];
        
        imageView.frame = CGRectOffset(imageView.frame, scrollWidth * i, 0);
        dataView.frame  = CGRectOffset(dataView.frame , scrollWidth * i, 0);
        [self.scrollView addSubview:imageView];
        [imageView release];
        [self.scrollView addSubview:dataView];
        [dataView release];
    }
    
    [self.scrollView setContentOffset:CGPointMake(scrollWidth, 0)];
    
    
}

- (NSMutableArray *)getCurrentFundArrayWithCurpage:(int)page
{
    int pre = [self validPageValue:curPage-1];
    int last = [self validPageValue:curPage+1];
    if([self.currentFundArray count] != 0) [self.currentFundArray removeAllObjects];
    [self.currentFundArray addObject:[self.fundDataArray objectAtIndex:pre-1]];
    [self.currentFundArray addObject:[self.fundDataArray objectAtIndex:curPage-1]];
    [self.currentFundArray addObject:[self.fundDataArray objectAtIndex:last-1]];
    return self.currentFundArray;
}
- (int)validPageValue:(NSInteger)value {
    if(value == 0) value = totalPage;                   // value＝1为第一张，value = 0为前面一张
    if(value == totalPage + 1) value = 1;
    return value;
}
-(void)downloadImage
{
    self.imageDownloader = [[[HXImageDownloader alloc] init] autorelease];
    self.imageDownloader.delegate = self;
    for (int i = 0; i<self.fundDataArray.count; i++) {
        HXFundTransferArrayModel * infoModel = (HXFundTransferArrayModel *)[self.fundDataArray objectAtIndex:i];
        if (infoModel.imagePath.length > 0) {
            NSString * userInfo = [NSString stringWithFormat:@"%d",i];
            [self.imageDownloader downloadImageWithURL:infoModel.imagePath userInfo:userInfo];
        }
    }
}
#pragma mark-
#pragma mark imageDownloader delegate
-(void)imageDownLoaderAtUserInfo:(id)userInfo image:(UIImage *)image
{
    NSInteger index = [userInfo intValue];
    HXFundTransferArrayModel * infoModel = (HXFundTransferArrayModel *)[self.fundDataArray objectAtIndex:index];
    infoModel.fundImage = image;
    [self refreshScrollView];
}
#pragma mark-
#pragma mark- scrollView delegate
-(void)scrollViewDidScroll:(UIScrollView *)ascrollView
{
    int x = ascrollView.contentOffset.x;
    if(x >= (2*scrollWidth)) {  // 往后翻一张
        curPage = [self validPageValue:curPage+1];
        [self refreshScrollView];
    }
    if(x <= 0) {                //往前翻一张
        curPage = [self validPageValue:curPage-1];
        [self refreshScrollView];
    }
    if ([self.delegate respondsToSelector:@selector(HXScrollFundViewDelegate:didScrollImageView:)]) {
        int index = (isSpecial && curPage > 2) ? curPage - 2:curPage;
        [self.delegate HXScrollFundViewDelegate:self didScrollImageView:index];
    }
}
-(void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    [scrollView setContentOffset:CGPointMake(scrollWidth, 0) animated:YES];
}
- (void)handleTap:(UITapGestureRecognizer *)tap {
    if ([self.delegate respondsToSelector:@selector(HXScrollFundViewDelegate:didSelectImageView:)]) {
        [self.delegate HXScrollFundViewDelegate:self didSelectImageView:curPage];
    }
}

@end
